package com.example.leetcode.high;

import java.util.ArrayList;
import java.util.List;

public class Solution2 {
    /**
     * 123
     * 456
     * 789
     *
     * @param args
     */
    public static void main(String[] args) {
        int[][] matrix = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        List<Integer> list = new Solution2().spiralOrder(matrix);
        System.out.println(list.size());
        list.forEach(integer -> {
            System.out.print(integer + "\t");
        });
    }

    public List<Integer> spiralOrder(int[][] matrix) {
        int x = 0, y = 0, m = matrix[0].length - 1, n = matrix.length - 1, right = 1, down = 2, left = 3, up = 4, direction = right;
        List<Integer> output = new ArrayList<>();
        while (output.size() < matrix[0].length * matrix.length) {
            if (direction == right) {
                boolean move = false;
                for (int i = x; i <= m; i++) {
                    move = true;
                    output.add(matrix[x][i]);
                }
                x++;
                direction = down;
                if (!move) {
                    break;
                }
            }
            if (direction == down) {
                boolean move = false;
                for (int i = y + 1; i <= n; i++) {
                    move = true;
                    output.add(matrix[i][m]);
                }
                m--;
                direction = left;
                if (!move) {
                    break;
                }
            }
            if (direction == left) {
                boolean move = false;
                for (int i = m; i >= x - 1; i--) {
                    move = true;
                    output.add(matrix[n][i]);
                }
                n--;
                direction = up;
                if (!move) {
                    break;
                }
            }
            if (direction == up) {
                boolean move = false;
                for (int i = n; i > y; i--) {
                    move = true;
                    output.add(matrix[i][y]);
                }
                y++;
                direction = right;
                if (!move) {
                    break;
                }
            }
        }
        return output;
    }
}
